package com.sync.syncmasterdata.customer.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sync.syncmasterdata.configuration.ConfInfo;
import com.sync.syncmasterdata.customer.pojo.GspCustomer;
import com.sync.syncmasterdata.customer.entity.oa.OACustomerEntity;
import com.sync.syncmasterdata.customer.entity.oa.OACustomerWFEntity;
import com.sync.syncmasterdata.customer.entity.wms.WmsCustomer;
import com.sync.syncmasterdata.customer.pojo.*;
import com.sync.syncmasterdata.customer.pojo.oa.ResponseCustomerXmlOaRoot;
import com.sync.syncmasterdata.customer.repository.oarep.OACustomerRepository;
import com.sync.syncmasterdata.customer.repository.oarep.OACustomerWFRepository;
import com.sync.syncmasterdata.customer.repository.oarep.UpdateOACustomerRepository;
import com.sync.syncmasterdata.customer.repository.u8rep.CustomerRepository;
import com.sync.syncmasterdata.customer.service.SyncService;
import com.sync.syncmasterdata.customer.service.http.HttpAPIServiceForCrmSync;
import com.sync.syncmasterdata.dingrobot.service.DingAPIService;
import com.sync.syncmasterdata.dingrobot.service.DingRobotService;
import com.sync.syncmasterdata.util.AuthUtil;
import com.sync.syncmasterdata.util.ConvertUtil;
import com.sync.syncmasterdata.util.NormalUtil;

import com.sync.syncmasterdata.vendor.entity.oa.ManulVendor;
import com.sync.syncmasterdata.vendor.repository.oarep.OAManulVendorRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.HtmlUtils;

import javax.transaction.Transactional;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.*;

import static com.sync.syncmasterdata.util.NormalUtil.*;

/**
 * 推送同步核心服务 客户同步用
 */
@Transactional
@Service
@Slf4j
public class SyncServiceImpl implements SyncService {

    @Autowired
    private HttpAPIServiceForCrmSync httpAPIService;
    @Autowired
    private DingAPIService dingAPIService;
    @Autowired
    private ConfInfo confInfo;
    @Autowired
    private RequestOACustomer requestOACustomer;
    @Autowired
    private ObjectMapper objectMapper;
//    @Autowired
//    private WmsCustomerRepository wmsCustomerRepository;
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private OACustomerRepository oaCustomerRepository;
    @Autowired
    private UpdateOACustomerRepository updateOACustomerRepository;
    @Autowired
    private OACustomerWFRepository oaCustomerWFRepository;
    @Autowired
    private OAManulVendorRepository oaManulVendorRepository;
    @Autowired
    private DingRobotService dingRobotService;
    @Autowired
    private AuthUtil authUtil;

    @Value("${maycur.url}")
    private String maycurUrl;
    @Value("${gsp.url}")
    private String GSPURL;

    /**
     * U8 openapi用 静态变量(配套 新增、更新用)
     */
    private final String FROM_ACCOUNT = "biosanu8";
    private final String TO_ACCOUNT = "biosanu8";
    //客户同步key
    private final String CUS_APP_KEY = "opa77b093bcbce40729";
//    private final String CUS_APP_SECRET = "08ac4444d99348598892c3882eb73d48";

    /**
     * 获取crm档案信息 by Guid
     *
     * @param guid
     * @return
     */
    @Override
    public CrmCustomer getCrmAccount(String guid) {
        String url = String.format("%s%s(%s)", confInfo.getCrmurl(), "accounts", guid);
        try {
            String responseStr = this.httpAPIService.doGetCrm(url);
            CrmCustomer customer = objectMapper.readValue(responseStr, CrmCustomer.class);
            log.info("获取客户档案为：{}-guid---{}", customer.toString(), guid);
            return customer;
        } catch (Exception ex) {
            ex.printStackTrace();
            log.info("获取客户档案catch异常：guid-{}", guid);

        }
        return null;
    }

    /**
     * 获取crm档案信息 by Name
     *
     * @param name
     * @return
     */
    public String getCrmAccountByName(String name) {
        String url = String.format("%s%s?$filter=name eq '%s'", confInfo.getCrmurl(), "accounts", name);
        try {
            url = encodeUrl(url);
            String ret = this.httpAPIService.doGetCrm(url);
            JSONObject rsqJson = new JSONObject(ret);
            JSONArray rsqArray = rsqJson.getJSONArray("value");
            if (rsqArray.length() == 0 || rsqArray.length() > 1) {
                return "";
            }
            JSONObject cusObj = rsqArray.getJSONObject(0);
            String guid = cusObj.get("accountid").toString();

            log.info("获取客户档案为：{}-guid{}", guid);
            return guid;
        } catch (Exception ex) {
            ex.printStackTrace();
            return "error";
        }
    }


    /**
     * 更新U8 客户信息
     *
     * @param cus
     * @return
     */
    @Override
    public String pushU8AccountForEdit(U8Customer cus, String ds_s) {
        String to_account = "biosanu8";
        String token = authUtil.getCPTokenByTag("u8cussync");
        String requestUrl = confInfo.getU8opeapiurl() + "api/customer/edit?from_account=" + FROM_ACCOUNT + "&to_account=" + TO_ACCOUNT + "&app_key=" + CUS_APP_KEY + "&token=" + token + "&ds_sequence=" + ds_s;

        try {
            Map<String, Object> map = new HashMap<>();
            map.put("customer", cus);
            String requestEntity = objectMapper.writeValueAsString(map);
            log.info("客户更新待传入json:{}", requestEntity);
            String responseStr = httpAPIService.doPost(requestUrl, requestEntity);
            log.info("请求返回json:{}", responseStr);
            JSONObject jsonObject = new JSONObject(responseStr);
            if (jsonObject.get("errcode").equals("0")) {
                return jsonObject.get("id").toString();
            } else {
                //异常推送钉钉报警
                dingRobotService.simpleDingSendMsg("推送U8客户信息（更新）出错：" + jsonObject.get("errmsg").toString(),new String[]{"15267167276"});
                log.info("推送U8客户信息（更新）出错：{}", jsonObject.get("errmsg").toString());
                return null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 更新oa 客户对象信息
     *
     * @param oa
     * @param id
     * @return
     */
    @Override
    public String updateOaAccount(OACustomer oa, String id) {
        String requestUrl = this.confInfo.getOaurl();
        //oa对象转 xml
        String requestxml_unencode = this.requestOACustomer.convertRequestObj(oa, id);
        //转编码
        String requestxml = ConvertUtil.addOaRequestHeader(NormalUtil.htmlEncode(requestxml_unencode));
        try {
            String response_encode = this.httpAPIService.doPost(requestUrl, requestxml);
            //转义结果
            String responseString = HtmlUtils.htmlUnescape(response_encode);
            //截取字符串
            responseString = NormalUtil.subString(responseString, "<ns1:out>", "</ns1:out>");
            JAXBContext jaxbContext = JAXBContext.newInstance(ResponseCustomerXmlOaRoot.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            ResponseCustomerXmlOaRoot responseCustomerXmlOaRoot = (ResponseCustomerXmlOaRoot) unmarshaller.unmarshal(new StringReader(responseString));
            if (responseCustomerXmlOaRoot.getOaReturn().getReturnmessage().contains("操作成功")) {
                return responseCustomerXmlOaRoot.getOaReturn().getId();
            } else {
                return "OA添加客户信息失败!" + responseCustomerXmlOaRoot.getOaReturn().getReturnmessage();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return "OA更新客户异常";
        }
    }

    /**
     * 更新crm客户档案信息（部分字段）
     *
     * @param requestObj
     * @param guid
     * @return
     */
    @Override
    public CrmCustomer updateCrmAccount(Map<String, Object> requestObj, String guid) {
        //使用传入str进行更新
        String url = String.format("%s%s(%s)", confInfo.getCrmurl(), "accounts", guid);
        try {
            //请求
            String responseStr = this.httpAPIService.doUpdateCrm(url, objectMapper.writeValueAsString(requestObj));
            if (responseStr != null) {
                //成功
                CrmCustomer customer = objectMapper.readValue(responseStr, CrmCustomer.class);
                return customer;
            } else {
                return null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();

        }
        return null;
    }

    /**
     * 获取u8openapi token
     * 不再使用直接获取token的方法
     * @return
     */
    private String getToken(String app_key,String app_secret) {
        String requestUrl = String.format("%s%s?from_account=%s&app_key=%s&app_secret=%s", confInfo.getU8opeapiurl(), "system/token", FROM_ACCOUNT, app_key, app_secret);
        try {
            JSONObject jsonObject = new JSONObject(httpAPIService.doGet(requestUrl));
            if (jsonObject.get("errcode").equals("0")) {
                JSONObject responseStr = (JSONObject) jsonObject.get("token");
                return responseStr.get("id").toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
        return null;
    }

    /**
     * 获取tradeid
     *
     * @param token
     * @return
     */
    private String getTradeid(String token,String app_key) {
        String requestUrl = String.format("%s%s?from_account=%s&app_key=%s&token=%s", confInfo.getU8opeapiurl(), "system/tradeid", FROM_ACCOUNT, app_key, token);
        try {
            JSONObject jsonObject = new JSONObject(httpAPIService.doGet(requestUrl));
            if (jsonObject.get("errcode").equals("0")) {
                JSONObject responseStr = (JSONObject) jsonObject.get("trade");
                return responseStr.get("id").toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
        return null;
    }

    /**
     * 推送 u8 新增客户 使用openapi
     *
     * @param cus
     * @param ds_s 测试为1，正式为2,安迈为3
     * @return
     */
    @Override
    public String pushU8AccountForAdd(U8Customer cus, String ds_s) {
        String to_account = "biosanu8";
//        String token = getToken(CUS_APP_KEY,CUS_APP_SECRET);
        String token = authUtil.getCPTokenByTag("u8cussync");
        String tradeid = getTradeid(token,CUS_APP_KEY);
        String sync = "1";
        String requestUrl = confInfo.getU8opeapiurl() + "api/customer/add?from_account=" + FROM_ACCOUNT + "&to_account=" + TO_ACCOUNT + "&app_key=" + CUS_APP_KEY + "&token=" + token + "&ds_sequence=" + ds_s + "&tradeid=" + tradeid + "&sync=" + sync;

        try {
            Map<String, Object> map = new HashMap<>();
            map.put("customer", cus);
            String requestEntity = objectMapper.writeValueAsString(map);
            log.info("客户新增待传入json:{}", requestEntity);
            log.info("请求新增客户url：{}", requestUrl);
            String responseStr = this.httpAPIService.doPost(requestUrl, requestEntity);
            log.info("请求返回json:{}", responseStr);
            JSONObject jsonObject = new JSONObject(responseStr);
            if (jsonObject.get("errcode").equals("0")) {
                return jsonObject.get("id").toString();
            } else {
                //推送异常
                log.info("推送U8客户信息（新增）出错：{}", jsonObject.get("errmsg").toString());
                //异常推送钉钉报警
                dingRobotService.simpleDingSendMsg("推送U8客户信息（新增）出错：" + jsonObject.get("errmsg").toString(), new String[]{"15267167276"});

                if (jsonObject.getString("errmsg").contains("已经存在")) {
                    //已经存在，通过sql获取 返回U8id
                    String _s = this.customerRepository.getCusCode(cus.getName());
                    dingRobotService.simpleDingSendMsg("U8客户新增接口操作取消，转数据库查询(getCusCode)：" + _s, new String[]{"15267167276"});
                    return _s;
                } else {
                    return null;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * crm 新增 oa 客户档案
     *
     * @param cus
     * @return
     */
    @Override
    public String pushOaAccountForAdd(OACustomer cus) {
        //验重OA客户信息(通过sql验重)
        String _kh = checkOaCustomer(cus.getKehumc());
        if (!"".equals(_kh)) {
            //已经存在，直接返回对应的客户code
            log.info("prod=add,oa新增部分,客户已经存在oa，直接返回oa客户编码");
            return _kh;

        }
        //不存在新增
        String requestUrl = this.confInfo.getOaurl();
        //oa对象转 xml
        String requestxml_unencode = this.requestOACustomer.convertRequestObj(cus, "");
        //转编码
        String requestxml = ConvertUtil.addOaRequestHeader(NormalUtil.htmlEncode(requestxml_unencode));
        try {
            String response_encode = this.httpAPIService.doPost(requestUrl, requestxml);
            //转义结果
            String responseString = HtmlUtils.htmlUnescape(response_encode);
            //截取字符串
            responseString = NormalUtil.subString(responseString, "<ns1:out>", "</ns1:out>");
            JAXBContext jaxbContext = JAXBContext.newInstance(ResponseCustomerXmlOaRoot.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            ResponseCustomerXmlOaRoot responseCustomerXmlOaRoot = (ResponseCustomerXmlOaRoot) unmarshaller.unmarshal(new StringReader(responseString));
            if (responseCustomerXmlOaRoot.getOaReturn().getReturnmessage().contains("操作成功")) {
                return responseCustomerXmlOaRoot.getOaReturn().getId();
            } else {
                //钉钉报警
                this.dingRobotService.simpleDingSendMsg("OA添加客户信息失败!" + responseCustomerXmlOaRoot.getOaReturn().getReturnmessage(),new String[]{"15267167276"});
                return "OA添加客户信息失败!" + responseCustomerXmlOaRoot.getOaReturn().getReturnmessage();
            }
        } catch (Exception ex) {
            ex.printStackTrace();

            this.dingRobotService.simpleDingSendMsg("OA添加客户异常",new String[]{"15267167276"});
            return "OA添加客户异常";
        }

    }

    /**
     * 获取U8 客户信息
     * 传入编码
     */
    public U8Customer getU8Customer(String code, String ds_s) {
        String to_account = "biosanu8";
        String token = authUtil.getCPTokenByTag("u8cussync");
        String requestUrl = confInfo.getU8opeapiurl() + "api/customer/get?from_account=" + FROM_ACCOUNT + "&to_account=" + TO_ACCOUNT + "&app_key=" + CUS_APP_KEY + "&token=" + token + "&ds_sequence=" + ds_s + "$id=" + code;
        try {

            String repStr = httpAPIService.doGet(requestUrl);
            JSONObject jsonObject = new JSONObject(repStr);
            if (jsonObject.get("errcode").equals("0")) {
                U8Customer u8Customer = objectMapper.readValue(jsonObject.get("customer").toString(), U8Customer.class);
                return u8Customer;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }


    /**
     * crm 推送新增斐创wms 客户 不再使用
     *
     * @param wms
     * @return
     */
    @Deprecated
    public String pushWmsAccountForAdd(WmsCustomer wms) {
        String guid1=checkWMSCustomer(wms.getSName());
        if (StringUtils.isBlank(guid1)) {
            //新增 wms客户信息
//            WmsCustomer newWmsCus = wmsCustomerRepository.save(wms);
            WmsCustomer newWmsCus = null;
            return newWmsCus.getUGuid1();
        }else{
            return guid1;
        }
    }

    /**
     * 推送时空智友 GSP 系统
     */
    public String pushGspAccountForAdd(GspCustomer gspCustomer) {
        String url = GSPURL + "/ts/openapi/putBusiness";
        List<GspCustomer> list = new ArrayList<>();
        list.add(gspCustomer);
        Map<String,Object> reqJson = new HashMap<>();
        reqJson.put("bscArch", list);
        try {
            //请求推送
            RestTemplate restTemplate = new RestTemplate();
            //中文乱码问题
            restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            log.info("请求报文---->{}", objectMapper.writeValueAsString(reqJson));
//        HttpEntity<Map<String, Object>> request = new HttpEntity<>(reqJson, headers);
            String resJson = restTemplate.postForObject(url, reqJson ,String.class);
            log.info("增加GSP 客户信息-------->{}", resJson);
            return resJson;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 查询wms是否有重复客户
     */
    public String checkWMSCustomer(String sName) {
        String kehumc = null;
//        String kehumc = wmsCustomerRepository.getKhInfo(sName);
        try {
            if (kehumc == null || "".equals(null2String(kehumc))) {
                return null;
            } else {
                return kehumc;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }

    }

    public List<ManulVendor> getManulVendor(){
        List<ManulVendor> lists = oaManulVendorRepository.getManulVendor();
        return lists;

    }

    /**
     * 查询oa是否有重复客户 "" "xxxx"
     *
     * @param sName
     * @return
     */
    public String checkOaCustomer(String sName) {
        return null2String(this.oaCustomerRepository.getCustomerID(sName));
    }

    /**
     * 查询erp中是否存在此客户
     */
    public String checkErpCustomer(String sName) {
        return null2String(this.customerRepository.getCusCode(sName));
    }

    /**
     * 查询erp中是否存在此客户
     */
    public Map<String, Object> checkErpCustomerBySingel(String sName) {
        Map<String, Object> map = this.customerRepository.getCusCodeAndStop(sName);
        if (map.isEmpty()) {
            return null;
        }
        return map;
    }


    /*
     * --------------------------以下区域为 手动同步服务区域 -------------------
     */
    /**
     * 获取ERP客户信息,双条件
     * 更新操作在service完成
     *
     * @param _crm
     * @return
     */
    public Map<String, String> getErpCus(CrmCustomer _crm) {
        Map<String, String> rMap = new HashMap<>();
        List<String> erpCusList = this.customerRepository.getCusCodeByNameAndGuid(_crm.getName(), _crm.getAccountid());

        if (erpCusList.size() == 1) {
            //符合条件的只有一个
            rMap.put("state", "1");
            rMap.put("code", "更新crm客户信息成功");
            //调用 crm档案更新 updateCrmAccount
            Map<String, Object> _map = new HashMap<>();
            _map.put("new_erp_num", erpCusList.get(0));
            updateCrmAccount(_map, _crm.getAccountid());

            return rMap;
        } else if (erpCusList.size() > 1) {
            //不符合条件
            rMap.put("state", "-1");
            rMap.put("code", "ERP系统中有多个客户信息符合条件，请检查ERP系统");
            return rMap;
        } else {
            rMap.put("state", "0");
            rMap.put("code", "ERP系统中没有此客户信息,可以考虑新建");
            return rMap;
        }
    }

    /**
     * 获取oa的客户信息（如果不存在，新增客户信息）
     * 更新操作在service完成
     *
     * @param _crm
     * @return
     */
    public Map<String, String> getOACus(CrmCustomer _crm) {
        Map<String, String> rMap = new HashMap<>();
        List<String> oaCusList = this.oaCustomerRepository.getCustomerIDByNameAndGuid(_crm.getName(), _crm.getAccountid());

        if (oaCusList.size() == 1) {
            //在oa中查询有一个符合的客户名称，回调crm更新客户档案接口
            rMap.put("state", "1");
            rMap.put("code", "更新OA客户信息成功");
            //调用 crm档案更新 updateCrmAccount
            Map<String, Object> _map = new HashMap<>();
            _map.put("new_oa_id", oaCusList.get(0));
            updateCrmAccount(_map, _crm.getAccountid());

            return rMap;
        } else if (oaCusList.size() > 1) {
            //不符合条件
            rMap.put("state", "-1");
            rMap.put("code", "OA系统中有多个客户信息符合条件，请检查OA系统");

            return rMap;
        } else {
            //插入oa客户信息
            rMap.put("state", "0");
            rMap.put("code", "OA系统中不存在客户信息，需要新增");
            return rMap;
        }

    }

    /**
     * 推送每刻 往来客商信息
     * 传入每刻对象
     */
    public String pushMaycurPartener(MayCurPartner partner) throws Exception {
        String resultStr = "";
        resultStr = httpAPIService.doPost(maycurUrl, objectMapper.writeValueAsString(partner));
        log.info("每刻推送往来客户：{}", resultStr);
        return resultStr;
    }

    /**
     * 推送每刻 自定义档案信息（客户）
     * @return
     * @throws Exception
     */
    public String pushMaycurCustomerReference(Map<String,String> customer) throws Exception {
        String url="http://172.17.100.14:8189/maycurpivot/addCustomerToReference";
        String resultStr = "";
        resultStr = httpAPIService.doPost(url, objectMapper.writeValueAsString(customer));
        log.info("推送每刻自定义档案客户：{}", resultStr);
        return resultStr;
    }

    /**
     * 更新每刻 自定义档案信息（客户）
     * @param customer
     * @return 更新结果
     * @throws Exception
     */
    public String editMaycurCustomerReference(Map<String,String> customer) throws Exception {
        String url="http://172.17.100.14:8189/maycurpivot/editCustomerToReference";
        String resultStr = "";
        resultStr = httpAPIService.doPost(url, objectMapper.writeValueAsString(customer));
        log.info("更新每刻自定义档案客户：{}", resultStr);
        return resultStr;
    }

    /**
     * 更新crm中 new_erp_num 信息
     */
    public String asSyncErpnum() {
        Map<String, JSONObject> listObj = new HashMap<>();
        String reqUrl = this.confInfo.getCrmurl() + "accounts?$select=name,new_erp_num,new_oa_id&$filter=new_erp_num eq null and statecode eq 0";
        try {
            String repStr = this.httpAPIService.doGetCrm(reqUrl);
            JSONObject jsonObject1 = new JSONObject(repStr);
            JSONArray jsonArray = new JSONArray(jsonObject1.get("value").toString());

            int j = 0;
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);

                String customerStr = obj.get("name").toString();
                String customerCode = this.customerRepository.getCusCode(customerStr);


                if (customerCode != null) {
                    JSONObject obj2 = new JSONObject();
                    obj2.put("new_erp_num", customerCode);
                    listObj.put(obj.get("accountid").toString(), obj2);
                    j++;
                }
            }

            log.info("符合更新要求的对象为(只有crm有)：{}个", jsonArray.length());
            log.info("可以更新(new_erp_num)字段的客户有{}个,需更新的数据为：{}", j, listObj);

            //执行更新
            for (Map.Entry<String, JSONObject> entry : listObj.entrySet()) {
                String crmReqUrl = String.format("%saccounts(%s)", this.confInfo.getCrmurl(), entry.getKey());
                this.httpAPIService.doUpdateCrm(crmReqUrl, entry.getValue().toString());
                log.info("更新成功：{}", entry.getValue());
            }

            return "手动更新数据量为：" + j;

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "手动更新出错!";
    }


    /**
     * 更新crm中 new_erp_num 信息
     */
    public String asSyncOaId() {
        Map<String, JSONObject> listObj = new HashMap<>();
        String reqUrl = this.confInfo.getCrmurl() + "accounts?$select=name,new_erp_num,new_oa_id&$filter=new_oa_id eq null and statecode eq 0";
        try {
            String repStr = this.httpAPIService.doGetCrm(reqUrl);
            JSONObject jsonObject1 = new JSONObject(repStr);
            JSONArray jsonArray = new JSONArray(jsonObject1.get("value").toString());

            int j = 0;
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);

                String customerStr = obj.get("name").toString();
                String customerCode = this.oaCustomerRepository.getCustomerID(customerStr);


                if (customerCode != null) {
                    JSONObject obj2 = new JSONObject();
                    obj2.put("new_oa_id", customerCode);
                    listObj.put(obj.get("accountid").toString(), obj2);
                    j++;
                }
            }

            log.info("符合更新要求的对象为(crm+oa有但是oaid未回写)：{}个", jsonArray.length());
            log.info("可以更新(new_oa_id)字段的客户有{}个,需更新的数据为：{}", j, listObj);

            //执行更新
            for (Map.Entry<String, JSONObject> entry : listObj.entrySet()) {
                String crmReqUrl = String.format("%saccounts(%s)", this.confInfo.getCrmurl(), entry.getKey());
                this.httpAPIService.doUpdateCrm(crmReqUrl, entry.getValue().toString());
                log.info("更新成功：{}", entry.getValue());
            }

            return "手动更新数据量为：" + j;

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "手动更新出错!";
    }

    /**
     * 更新crm客户档案中，oaid字段
     */
    public String asSyncOaid2() {
        Map<String, JSONObject> listObj = new HashMap<>();
        String reqUrl = "http://172.16.0.190:5555/crm/api/data/v8.2/accounts?$select=name,new_erp_num,new_oa_id&$filter=new_erp_num ne null and new_oa_id eq null and statecode eq 0";
        try {
            String repStr = this.httpAPIService.doGetCrm(reqUrl);
            JSONObject jsonObject1 = new JSONObject(repStr);
            JSONArray jsonArray = new JSONArray(jsonObject1.get("value").toString());
            log.info("符合更新要求的对象为(erp_num存在，oa_id缺少)：{}个", jsonArray.length());
            int j = 0;
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);

                String customerStr = obj.get("name").toString();
                String customerCode = this.oaCustomerRepository.getCustomerID(customerStr);


                if (customerCode != null) {
                    JSONObject obj2 = new JSONObject();
                    obj2.put("new_oa_id", customerCode);
                    listObj.put(obj.get("accountid").toString(), obj2);
                    j++;
                }
            }

            log.info("可以更新的客户有{}个,需更新的数据为：{}", j, listObj);
            //执行更新

            for (Map.Entry<String, JSONObject> entry : listObj.entrySet()) {
                String crmReqUrl = String.format("http://172.16.0.190:5555/crm/api/data/v8.2/accounts(%s)", entry.getKey());
                this.httpAPIService.doUpdateCrm(crmReqUrl, entry.getValue().toString());
                log.info("更新(erp_num存在，oa_id缺少)成功：{}", entry.getValue());
            }

            return "手动更新数据量为：" + j;

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "手动更新出错!";
    }

    /**
     * oa流程转数据 转换 数据对象方法。
     * 用于oa流程触发推送（only 新增）
     */
    public OACustomer wfToMode(String requestid) {
        OACustomerEntity oaCustomerEntity = this.oaCustomerRepository.getOACustomerEntityByRequestid(requestid);
        if (oaCustomerEntity != null) {
            OACustomer oaCustomer = new OACustomer();
            oaCustomer.setId(String.valueOf(oaCustomerEntity.getId()));
            oaCustomer.setKehumc(oaCustomerEntity.getKehumc());
            oaCustomer.setZuizhongkehu(oaCustomerEntity.getZuizhongkehu());
            oaCustomer.setKehulx(oaCustomerEntity.getKehulx());
            oaCustomer.setQita(oaCustomerEntity.getQita());
            oaCustomer.setSheng(oaCustomerEntity.getSheng());
            oaCustomer.setShi(oaCustomerEntity.getShi());
            oaCustomer.setKehulb(oaCustomerEntity.getKehulb());
            oaCustomer.setShifouyzz(null2Int(oaCustomerEntity.getShifouyzz()));
            oaCustomer.setU8kehubm(oaCustomerEntity.getU8kehubm());
            oaCustomer.setU8VonderCode(oaCustomerEntity.getU8VonderCode());
            oaCustomer.setSuozaisf(null2Int(oaCustomerEntity.getSuozaisf()));
            oaCustomer.setSuozaics(null2Int(oaCustomerEntity.getSuozaics()));
            oaCustomer.setKaihuh(oaCustomerEntity.getKaihuh());
            oaCustomer.setKaihuzh(oaCustomerEntity.getKaihuzh());
            //账号去除空格
            oaCustomer.setZhanghao(NormalUtil.trimString(oaCustomerEntity.getZhanghao()));
            oaCustomer.setLianhangh(oaCustomerEntity.getLianhangh());
            oaCustomer.setKehuzt(0);
            return oaCustomer;
        } else {
            return null;
        }
    }

    /**
     * 新增客户失败（客户名称重复导致），从流程获取并转换:主要是更新
     * @param requestid
     * @return
     */
    public OACustomer wfToMode2(String requestid) {
        OACustomerWFEntity oacuswf = this.oaCustomerWFRepository.getOACustomerWFEntityByRequestid(requestid);
        OACustomerEntity oacusHas = this.oaCustomerRepository.getOACustomerU8ID(oacuswf.getKehumc());
        if(oacusHas!=null) {
            //已经存在
            if (StringUtils.isNotBlank(oacusHas.getU8kehubm())) {
                //u8已经存在 更新oa字段
                updateOACustomerRepository.updateOACus(Integer.valueOf(oacusHas.getId()), oacuswf.getKaihuzh(), oacuswf.getZhanghao(), oacuswf.getKaihuh(), oacuswf.getLianhangh());
                //返回
                oacusHas.setKaihuzh(oacuswf.getKaihuzh());
                oacusHas.setZhanghao(oacuswf.getZhanghao());
                oacusHas.setKaihuh(oacuswf.getKaihuh());
                oacusHas.setLianhangh(oacuswf.getLianhangh());
            }
            OACustomer oaCustomer = new OACustomer();
            oaCustomer.setId(String.valueOf(oacusHas.getId()));
            oaCustomer.setKehumc(oacusHas.getKehumc());
            oaCustomer.setZuizhongkehu(oacusHas.getZuizhongkehu());
            oaCustomer.setKehulx(oacusHas.getKehulx());
            oaCustomer.setQita(oacusHas.getQita());
            oaCustomer.setSheng(oacusHas.getSheng());
            oaCustomer.setShi(oacusHas.getShi());
            oaCustomer.setKehulb(oacuswf.getKehulb()); //客户类别 使用流程中的客户类别
            oaCustomer.setShifouyzz(null2Int(oacusHas.getShifouyzz()));
            oaCustomer.setU8kehubm(oacusHas.getU8kehubm());
            oaCustomer.setU8VonderCode(oacusHas.getU8VonderCode());
            oaCustomer.setSuozaisf(null2Int(oacusHas.getSuozaisf()));
            oaCustomer.setSuozaics(null2Int(oacusHas.getSuozaics()));
            oaCustomer.setKaihuh(oacusHas.getKaihuh());
            oaCustomer.setKaihuzh(oacusHas.getKaihuzh());
            //账号去除空格
            oaCustomer.setZhanghao(NormalUtil.trimString(oacusHas.getZhanghao()));
            oaCustomer.setLianhangh(oacusHas.getLianhangh());
            oaCustomer.setKehuzt(0);
            return oaCustomer;
        } else {
            return null;
        }
    }



}
